package com.ruoyi.web.controller.system;

import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.InstallationGuide;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IDeviceService;
import com.ruoyi.system.service.IInstallationGuideService;
import com.ruoyi.system.service.ISysDeptService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/installation_guide")
public class InstallationGuideController extends BaseController {
    @Autowired
    private IInstallationGuideService installationGuideService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    private AjaxResult checkExistance(InstallationGuide installationGuide) {
        Map<String, Object> existance = installationGuideService.findExistance(installationGuide);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "文件名称已经存在");
            }
            // Object file_of_type_exists = existance.get("file_of_type_exists");
            // if (file_of_type_exists != null && Integer.parseInt(file_of_type_exists.toString()) > 0) { 
            //     return AjaxResult.error(HttpStatus.ERROR, "该类型文件已经存在");
            // }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:installation_guide:add')")
    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @Log(title = "安装指导", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) InstallationGuide installationGuide) {
        QueryVo queryVo = new QueryVo();
        Integer deviceId = installationGuide.getDeviceId();
        if (deviceId > 0) {
            queryVo.filters.put("id", installationGuide.getDeviceId());
            Device device = deviceService.retrieve(queryVo);
            if (device == null) {
                return AjaxResult.error("没有找到指定的产品");
            }
        } else {
            installationGuide.setDeviceId(0);
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        installationGuide.setCompanyId(companyId);
        AjaxResult ret = checkExistance(installationGuide);
        if (ret != null) {
            return ret;
        }
        Integer id = installationGuideService.create(installationGuide);
        if (id != null) {
            return AjaxResult.success(installationGuide);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:installation_guide:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) InstallationGuide installationGuide) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("name", installationGuide.getName());
        queryVo.filters.put("description", installationGuide.getDescription());
        queryVo.filters.put("video_path", installationGuide.getVideoPath());
        queryVo.filters.put("file_path", installationGuide.getFilePath());
        queryVo.filters.put("device_sn", installationGuide.getDeviceSn());
        queryVo.filters.put("project_name", installationGuide.getProjectName());
        queryVo.filters.put("project_code", installationGuide.getProjectCode());
        queryVo.filters.put("device_name", installationGuide.getDeviceName());
        queryVo.filters.put("device_code", installationGuide.getDeviceCode());
        queryVo.filters.put("general", installationGuide.getGeneral());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<InstallationGuide> installationGuides = installationGuideService.index(queryVo);
        return getDataTable(installationGuides);
    }

    @PreAuthorize("@ss.hasPermi('system:installation_guide:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        queryVo.filters.put("company_id", companyId);
        InstallationGuide installationGuide = installationGuideService.retrieve(queryVo);
        if (installationGuide == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(installationGuide);
    }

    @PreAuthorize("@ss.hasPermi('system:installation_guide:edit')")
    @Log(title = "安装指导", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) InstallationGuide installationGuide)
    {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", installationGuide.getId());
        InstallationGuide target = installationGuideService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        installationGuide.setCompanyId(target.getCompanyId());
        installationGuide.setDeviceId(target.getDeviceId());
        AjaxResult ret = checkExistance(installationGuide);
        if (ret != null) {
            return ret;
        }
        if (installationGuideService.update(installationGuide)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:installation_guide:remove')")
    @Log(title = "安装指导", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("company_id", companyId);
        if (installationGuideService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
